package com.qf.efserver.user.personaldata.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.qf.common.core.entity.SleepRecords;
import com.qf.common.core.entity.SleepTime;
import com.qf.common.core.entity.Users;
import com.qf.common.core.utils.DateUtils;
import com.qf.common.core.utils.TokenUtils;
import com.qf.common.core.utils.UserUtils;
import com.qf.common.minio.utils.MinioUtil;
import com.qf.efserver.food.VO.FoodVO;
import com.qf.efserver.food.service.impl.FoodServiceImpl;
import com.qf.efserver.login.param.StatureParam;
import com.qf.efserver.sleep.service.SleepService;
import com.qf.efserver.user.personaldata.mapper.UsersMapper;
import com.qf.efserver.user.personaldata.param.UsersUpdateParam;
import com.qf.efserver.user.personaldata.service.UsersService;
import com.qf.efserver.user.personaldata.vo.UsersDataVO;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * ---做一个内核强大的人---
 *
 * @author HuaZi
 * @date 2024/11/8
 * @desc 希望我们都能遇到真诚的人
 */
@Service
public class UsersServiceImpl implements UsersService {
    @Resource
    private UsersMapper usersMapper;
    @Resource
    private FoodServiceImpl foodService;
    @Resource
    private SleepService sleepService;
    @Resource
    private MinioUtil minioUtil;
    @Lazy
    @Resource
    private UsersService usersService;

    @ApiOperation(value="获取用户详细信息", notes="根据id来获取用户详细信息")
    @Override
    public UsersDataVO getUserVO() {
        //通过UserUtils获取userid
        Integer uid = UserUtils.getUid();
        Users users = usersMapper.selectById(uid);
        UsersDataVO usersDataVO=new UsersDataVO();
        BeanUtils.copyProperties(users,usersDataVO);
        //通过出生日期修改年龄
        Date birthday = users.getBirthday();
        //出生那一年
        String year = DateUtils.formatDate(birthday, "yyyy");
        Integer byear = Integer.valueOf(year);
        //今年
        String today= DateUtils.formatDate(new Date(),"yyyy");
        Integer tyear = Integer.valueOf(today);
        Integer age=tyear-byear;
        usersDataVO.setAge(age);

        SleepTime sleepTime = sleepService.selectSleepByUserId();
        Integer times = sleepTime.getSleepTime();
        usersDataVO.setSleepTime(times);
        //调用获得用户一天所吃的食物的的千卡
        List<FoodVO> foodVOS = foodService.selectCFP();
        int sumCalorie=0;
        for (FoodVO foodVO : foodVOS) {
            sumCalorie=sumCalorie+foodVO.getSumCalories();
        }
        usersDataVO.setFoodCalories(sumCalorie);
        System.out.println(usersDataVO);
        return usersDataVO;
    }
    @ApiOperation(value = "修改用户密码",notes = "通过id和新密码来修改密码")
    @Override
    public void updatePassword(String password, String verifyPassword) {
        if(password==null || verifyPassword==null){
            throw new RuntimeException("输入的值不能为空");
        }
        if(!password.equals(verifyPassword)){
            throw new RuntimeException("两次密码不一致,请重试");
        }else {
            String s = SecureUtil.md5(password);
            usersMapper.update(null,
                    new LambdaUpdateWrapper<Users>()
                            .set(Users::getPassword,s)
                            .eq(Users::getUserId, UserUtils.getUid()));
        }
    }
    /**
     * 修改用户身材数据
     *
     * @param statureParam
     */
    @Override
    public void updateUserStature(StatureParam statureParam) {
        Integer uid = TokenUtils.getUidFromToken();
        Users users = new Users();
        BeanUtils.copyProperties(statureParam, users);
        usersMapper.update(users, new UpdateWrapper<Users>().eq("user_id", uid));
    }

    @Override
    public Users getUserInfo() {
        Integer uid = TokenUtils.getUidFromToken();
        return usersMapper.selectById(uid);
    }

    @Override
    public void updateUsers(UsersUpdateParam usersUpdateParam) {
        usersUpdateParam.setUserId(UserUtils.getUid());
        String s = DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        //根据修改出生日期修改年龄
        Integer uid = UserUtils.getUid();
        Users users = usersMapper.selectById(uid);
        //出生那一年
        String year = DateUtils.formatDate(users.getBirthday(), "yyyy");
        Integer byear = Integer.valueOf(year);
        //今年
        String today= DateUtils.formatDate(new Date(),"yyyy");
        Integer tyear = Integer.valueOf(today);
        Integer age=tyear-byear;
        try {
            date = sdf.parse(s);
            usersUpdateParam.setUpdateTime(date);
            usersMapper.updateUsers(usersUpdateParam);
            usersMapper.updateAge(uid,age);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public String upload(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String newFileName = uuid + originalFilename.substring(originalFilename.lastIndexOf("."));
        String path = null;
        try {
            path = minioUtil.upload(file.getInputStream(), newFileName, file.getContentType());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return path;
    }

    @Override
    public void updateWeight(Double weight) {
        usersMapper.update(null,
                new LambdaUpdateWrapper<Users>()
                        .set(Users::getWeight,weight)
                        .eq(Users::getUserId,UserUtils.getUid()));
    }

    @Override
    public Users getUser(Integer id) {
        return usersMapper.selectById(id);
    }

}
